package com.qf.user.filter;


import com.qf.user.entity.User;
import com.qf.user.util.JWTUtil;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 职责
 * 解析jwt令牌
 */
public class TokenFilter extends BasicAuthenticationFilter {
    public TokenFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {

        //1:获取令牌
        String token = request.getHeader("token");


        try {
            //priciple
            User user = JWTUtil.verifyToken(token);
            //获取用户的权限列表
            Collection<SimpleGrantedAuthority> authorities = new ArrayList<>();
            List<String> menus = user.getMenus();

            for (String menu : menus) {
                authorities.add(new SimpleGrantedAuthority(menu));
            }

            //遍历角色
            for (String role : user.getRoles()) {
                authorities.add(new SimpleGrantedAuthority(role));
            }


            //将用户信息存放到securityContext中
            UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken
                    = new UsernamePasswordAuthenticationToken(user,null,authorities);

            SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);


        }catch (Exception ex){
            //ex.printStackTrace();
        }

        //放行
        chain.doFilter(request,response);

        //清空
        SecurityContextHolder.clearContext();
    }
}
